layui.define(['layer', 'table'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;

    var treetable = {
        // 渲染树形表格
        render: function (param) {
            param.url = param.url || '';
            param.data = param.data || [];
            param.tree = param.tree || {};
            if (!param.tree.iconIndex) param.tree.iconIndex = 2;
            if (!param.tree.isPidData) param.tree.isPidData = false;
            if (!param.tree.idName) param.tree.idName = 'id';
            if (!param.tree.pidName) param.tree.pidName = 'parentId';
            if (!param.treeIdName) param.treeIdName = 'id';
            if (!param.treePidName) param.treePidName = 'parentId';
            param.defaultToolbar = param.defaultToolbar || ['filter', 'exports', 'print'];
            param.page = param.page || false;
            param.height = param.height || 'full-145';

            // 获取数据
            if (param.data.length > 0) {
                this.init(param);
            } else {
                $.getJSON(param.url, function (res) {
                    param.data = res.data;
                    this.init(param);
                }.bind(this));
            }
        },

        // 初始化表格
        init: function (param) {
            var data = param.data;
            if (param.tree.isPidData) {
                data = this.pidToChildren(data, param.tree.idName, param.tree.pidName);
            }
            param.cols[0][param.tree.iconIndex]['templet'] = function (d) {
                var mIcon = '';
                var tbody = $(param.elem).next().find('tbody');
                if (tbody.find('tr[data-index="' + d.LAY_INDEX + '"]').find('.layui-table-tree-icon').length > 0) {
                    if (tbody.find('tr[data-index="' + d.LAY_INDEX + '"]').find('.layui-table-tree-icon').hasClass('layui-table-tree-icon-open')) {
                        mIcon = '<i class="layui-icon layui-icon-triangle-d"></i>';
                    } else {
                        mIcon = '<i class="layui-icon layui-icon-triangle-r"></i>';
                    }
                }
                return '<span style="padding-left:' + (d[param.treeIdName].toString().split('-').length - 1) * 15 + 'px"></span>' + mIcon + d[param.cols[0][param.tree.iconIndex].field];
            };

            param.data = this.treeToFlat(data, param.treeIdName, param.treePidName);
            table.render(param);
            this.bindEvents(param);
        },

        // pid形式数据转children形式
        pidToChildren: function (data, idName, pidName) {
            var res = [];
            var temp = {};
            for (var i = 0; i < data.length; i++) {
                temp[data[i][idName]] = data[i];
            }
            for (var k = 0; k < data.length; k++) {
                if (temp[data[k][pidName]] && data[k][idName] != data[k][pidName]) {
                    if (!temp[data[k][pidName]].children) {
                        temp[data[k][pidName]].children = [];
                    }
                    temp[data[k][pidName]].children.push(data[k]);
                } else {
                    res.push(data[k]);
                }
            }
            return res;
        },

        // 树形数据转换为表格数据
        treeToFlat: function (data, idName, pidName, prefix) {
            var res = [];
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var mId = prefix ? prefix + '-' + i : i + '';
                item[idName] = mId;
                item[pidName] = prefix || '0';
                res.push(item);
                if (item.children) {
                    var children = this.treeToFlat(item.children, idName, pidName, mId);
                    res = res.concat(children);
                }
            }
            return res;
        },

        // 绑定事件
        bindEvents: function (param) {
            var that = this;
            var $elem = $(param.elem).next();
            // 展开/折叠
            $elem.on('click', '.layui-table-tree-icon', function () {
                var tr = $(this).closest('tr');
                var td = $(this).closest('td');
                var key = tr.data('index');
                if ($(this).hasClass('layui-table-tree-icon-open')) {
                    $(this).removeClass('layui-table-tree-icon-open');
                    that.hide(param, key);
                } else {
                    $(this).addClass('layui-table-tree-icon-open');
                    that.show(param, key);
                }
                return false;
            });
        },

        // 展开所有
        expandAll: function (elem) {
            $(elem).next().find('.layui-table-tree-icon').addClass('layui-table-tree-icon-open');
            $(elem).next().find('tr').removeClass('layui-hide');
        },

        // 折叠所有
        foldAll: function (elem) {
            $(elem).next().find('.layui-table-tree-icon').removeClass('layui-table-tree-icon-open');
            $(elem).next().find('tr[data-type="child"]').addClass('layui-hide');
        },

        // 隐藏子节点
        hide: function (param, key) {
            var that = this;
            var $elem = $(param.elem).next();
            var tr = $elem.find('tr[data-index="' + key + '"]');
            var td = tr.find('td[data-field="' + param.cols[0][param.tree.iconIndex].field + '"]');
            var icon = td.find('.layui-table-tree-icon');
            if (icon.hasClass('layui-table-tree-icon-open')) {
                icon.removeClass('layui-table-tree-icon-open');
            }
            var children = this.getChildren(param, key);
            for (var i = 0; i < children.length; i++) {
                $elem.find('tr[data-index="' + children[i] + '"]').addClass('layui-hide');
                that.hide(param, children[i]);
            }
        },

        // 显示子节点
        show: function (param, key) {
            var that = this;
            var $elem = $(param.elem).next();
            var tr = $elem.find('tr[data-index="' + key + '"]');
            var children = this.getChildren(param, key);
            for (var i = 0; i < children.length; i++) {
                $elem.find('tr[data-index="' + children[i] + '"]').removeClass('layui-hide');
                var td = $elem.find('tr[data-index="' + children[i] + '"]').find('td[data-field="' + param.cols[0][param.tree.iconIndex].field + '"]');
                var icon = td.find('.layui-table-tree-icon');
                if (icon.hasClass('layui-table-tree-icon-open')) {
                    that.show(param, children[i]);
                }
            }
        },

        // 获取所有子节点
        getChildren: function (param, key) {
            var that = this;
            var $elem = $(param.elem).next();
            var tr = $elem.find('tr[data-index="' + key + '"]');
            var pid = tr.attr('data-index');
            var children = [];
            $elem.find('tr').each(function () {
                if ($(this).attr('data-index').toString().indexOf(pid + '-') === 0) {
                    children.push($(this).attr('data-index'));
                }
            });
            return children;
        }
    };

    exports('treetable', treetable);
}); 